//
//  DBManager.m
//  Model
//
//  Created by yull on 14/10/28.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "DBManager.h"

#import "AppDelegate.h"
#import "PrivateMsgDao.h"
#import "UserDao.h"
#import "ChatInfoDao.h"
#import "GroupMsgDao.h"
#import "ChatSysInfoDao.h"
#import "PlanDao.h"

@implementation DBManager

+ (instancetype)shareInstance
{
    static DBManager *dbManager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        dbManager = [[DBManager alloc] init];
    });
    return dbManager;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.daoArray = [NSArray arrayWithObjects:
                         [PrivateMsgDao shareInstance],
                         [GroupMsgDao shareInstance],
                         [UserDao shareInstance],
                         [ChatInfoDao shareInstance],
                         [ChatSysInfoDao shareInstance],
                         [PlanDao shareInstance],
                         nil];
    }
    return self;
}

- (BOOL)openDataBaseWithPath:(NSString *)dbPath
{
    if ([self checkDBFileExistAtPath:dbPath]) {
        
        if (self.dbQueue) {
            
            if ([self.dbQueue.path isEqualToString:dbPath]) {
                return YES;
            }
            
            [self.dbQueue close];
        }
        
        self.dbQueue = [[FMDatabaseQueue alloc] initWithPath:dbPath flags:SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
        
        for (BaseDao *dao in self.daoArray) {
            [dao createTable];
        }
        
        [self clearChatRequest];
    }
    return YES;
}

- (BOOL)checkDBFileExistAtPath:(NSString *)dbPath
{
    BOOL ret = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:dbPath]) {
        ret = [fileManager createFileAtPath:dbPath contents:nil attributes:nil];
        if (!ret) {
            NSLog(@"db file create fail at path = %@!",dbPath);
        }
    }
    return ret;
}

- (void)openDataBaseByUserId:(UInt64)userId
{
    NSString *dbPath = [NSString stringWithFormat:@"%@/Documents/db/%lld.sqlite",NSHomeDirectory(),userId];
    NSLog(@"数据库路径=%@",dbPath);
    [self openDataBaseWithPath:dbPath];
}

- (void)closeDataBase
{
    if (self.dbQueue) {
        [self.dbQueue close];
        
        self.dbQueue = nil;
    }
}

- (void)clearChatRequest
{
    [[PrivateMsgDao shareInstance] clearSendingMessageToFail];
    [[GroupMsgDao shareInstance] clearSendingMessageToFail];
}

@end
